#include "network/stdio_stream.hpp"

#include <cstdio>
#include <unistd.h>

namespace ibox::network {

StdinStream::StdinStream(event::Loop *loop) : m_buffd(loop->ptr()) {
    Fd stdin_fd{STDIN_FILENO};
    m_buffd.initialize(stdin_fd, BufferedFd::ReadOnly);
}

void StdinStream::set_receive_callback(ReceiveCallback cb, size_t threshold) {
    m_buffd.set_receive_callback(cb, threshold);
}

bool StdinStream::enable() { return m_buffd.enable(); }

bool StdinStream::disable() { return m_buffd.disable(); }

StdoutStream::StdoutStream(event::Loop *loop) : m_buffd(loop->ptr()) {
    Fd stdout_fd{STDOUT_FILENO};
    m_buffd.initialize(stdout_fd, BufferedFd::WriteOnly);
}

bool StdoutStream::send(const void *data_ptr, size_t data_size) {
    return m_buffd.send(data_ptr, data_size);
}

bool StdoutStream::enable() { return m_buffd.enable(); }

bool StdoutStream::disable() { return m_buffd.disable(); }

StdioStream::StdioStream(event::Loop *loop)
    : m_in_buffd(loop->ptr()), m_out_buffd(loop->ptr()) {
    Fd stdin_fd{STDIN_FILENO};
    Fd stdout_fd{STDOUT_FILENO};
    m_in_buffd.initialize(stdin_fd, BufferedFd::ReadOnly);
    m_out_buffd.initialize(stdout_fd, BufferedFd::WriteOnly);
}

void StdioStream::set_receive_callback(ReceiveCallback cb, size_t threshold) {
    m_in_buffd.set_receive_callback(cb, threshold);
}

bool StdioStream::send(const void *data_ptr, size_t data_size) {
    return m_out_buffd.send(data_ptr, data_size);
}

bool StdioStream::enable() {
    return m_in_buffd.enable() && m_out_buffd.enable();
}

bool StdioStream::disable() {
    return m_in_buffd.disable() && m_out_buffd.disable();
}

} // namespace ibox::network
